import React, { useCallback, useState, useEffect } from 'react';
import { useDetail } from '@/components/ApplyStep/utils';
import request from '@/utils/request';
import { Icon, message } from 'antd';
import { useDeepCompareEffect } from 'react-use';
import { history } from 'umi';
import { isMoment } from 'moment';

// 获取详情
export const useData = (portal, params) => {
    const url = portal ? '/api/oa/v1/leaveoffices/detail' : '/api/oa/v1/leaveoffices/personal/detail';
    const getData = useCallback(async () => {
        const response = await request(url, {
            method: 'POST',
            data: params
        });
        if (response.code === 10000) {
            return response.data;
        }
        message.error(response.msg);
        history.push('/personal/message/system');

        // return new Error(response.msg);
        return {
            currentProcessTaskInstance: {},
            relatedBusinessObject: {},
            processTaskInstances: [],
            processTaskTemplates: []
        };
    }, [params.processInstanceId, params.leaveOfficeId, params.processTemplateId]);
    const { loading, detail } = useDetail({
        getData
    });

    return {
        loading,
        detail
    };
};

// 获取员工状态处于入职中、试用、正式的员工
export const useEmployeeList = params => {
    const [loading, setLoading] = useState(false);
    const [employeeList, setEmployeeList] = useState([]);

    useDeepCompareEffect(() => {
        const fetchEmployeeList = async () => {
            if (!params.userName) return;
            setLoading(true);
            const response = await request('/api/oa/v1/employee/getemployeebycondition', {
                method: 'POST',
                data: params
            });
            if (response.code === 10000) {
                setEmployeeList(response.data || []);
            } else {
                setEmployeeList([]);
            }
            setLoading(false);
        };

        fetchEmployeeList();
    }, [params]);

    return {
        loading,
        employeeList
    };
};

// 获取直属下的员工
export const useUnderEmployeeList = params => {
    const [loading, setLoading] = useState(false);
    const [employeeList, setEmployeeList] = useState([]);

    useDeepCompareEffect(() => {
        const fetchEmployeeList = async () => {
            if (!params.userName) return;
            setLoading(true);
            const response = await request('/api/uc/org/employee/gethandoveremployeebycondition', {
                method: 'POST',
                data: params
            });
            if (response.code === 10000) {
                setEmployeeList(response.data || []);
            } else {
                setEmployeeList([]);
            }
            setLoading(false);
        };

        fetchEmployeeList();
    }, [params]);

    return {
        loading,
        employeeList
    };
};

// 获取字典
export const useDictionary = params => {
    const [loading, setLoading] = useState(false);
    const [dictionary, setDictionary] = useState([]);

    useDeepCompareEffect(() => {
        const fetchDictionary = async () => {
            if (!params.code && !params.codes) return;
            setLoading(true);
            const response = await request('/api/dict/v1/getList', {
                data: params,
                method: 'POST'
            });

            if (response.code === 10000) {
                setDictionary(response.data);
            }
            setLoading(false);
        };

        fetchDictionary();
    }, [params]);

    return {
        loading,
        dictionary
    };
};

export const findCompany = (data, id) => {
    let result = '';
    const find = tree => {
        tree.forEach(item => {
            if (item.id === id) {
                result = item;
            } else if (Array.isArray(item.children)) {
                find(item.children);
            }
        });
    };

    find(data);

    return result;
};

// 离职管理-获取离职通知期
export const useQuitNotice = userCode => {
    const [loading, setLoading] = useState(false);
    const [quitNotice, setQuitNotice] = useState({});

    useEffect(() => {
        const fetchQuitNotice = async () => {
            if (!userCode) return;
            setLoading(true);
            const response = await request(`/api/oa/v1/leaveoffices/quitnotice?userCode=${userCode}`);
            if (response.code === 10000) {
                setQuitNotice(response.data);
            }
            setLoading(false);
        };

        fetchQuitNotice();
    }, [userCode]);

    return {
        loading,
        quitNotice
    };
};

// 获取附件
export const useAttachment = id => {
    const [file, setFile] = useState([]);

    useEffect(() => {
        const fetchFile = async () => {
            if (!id) return;
            const response = await request(`/api/oa/v1/leaveoffices/file/${id}`);

            if (response.code === 10000) {
                setFile(response.data);
            } else {
                console.error(response.msg);
            }
        };
        fetchFile();
    }, [id]);

    return {
        file
    };
};
// 渲染附件
export const renderFiles = files => {
    if (files.length === 0) return '无';
    return files.map(item => (
        <div key={item.id}>
            <Icon style={{ marginRight: 4 }} type="link" />
            {item.originName}
            <a rel="noopener noreferrer" target="_blank" style={{ marginLeft: 8 }} href={item.url} download>
                查看
            </a>
        </div>
    ));
};

// 提供表单操作
export const useForms = ({
    form,
    leaveOfficeId,
    detail,
    processTemplateId,
    processInstanceId,
    otherPost,
    currentUser
}) => {
    const { currentProcessTaskInstance = {} } = detail;
    const { relatedBusinessObject = {} } = currentProcessTaskInstance;
    const [submitLoading, setSubmitLoading] = useState(false);
    const [rejectLoading, setRejectLoading] = useState(false);
    const [cancelLoading, setCancelLoading] = useState(false);
    const processPush = async data => {
        const response = await request('/api/oa/v1/system/process/push', {
            method: 'POST',
            data
        });
        return response;
    };
    const onlyCheck = async checkedEmployeeId => {
        const response = await request(
            `/api/oa/v1/leaveoffices/actions/onlycheck?employeeId=${checkedEmployeeId}` +
                `&userNo=${otherPost ? form.getFieldValue('userNo') : currentUser.userNo}`
        );
        return response;
    };
    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                setSubmitLoading(true);
                if (!leaveOfficeId) {
                    let checkEmployeeId = '';
                    if (leaveOfficeId) {
                        checkEmployeeId = relatedBusinessObject.employeeId;
                    } else {
                        checkEmployeeId = form.getFieldValue('employeeId');
                    }
                    const checkResponse = await onlyCheck(checkEmployeeId);
                    if (checkResponse.code !== 10000) {
                        message.error(checkResponse.msg);
                        setSubmitLoading(false);
                        return;
                    }
                }
                const tmpObj = {};
                Object.keys(values).forEach(propName => {
                    const value = values[propName];
                    if (propName === 'actualLeaveDateHr') {
                        // rc-from 不能通用字段名？，这里取个别名
                        tmpObj.actualLeaveDate = value.format('YYYY-MM-DD');
                    } else if (isMoment(value)) {
                        tmpObj[propName] = value.format('YYYY-MM-DD');
                    } else if (propName === 'resourceRelation') {
                        tmpObj[propName] = value && value.uploadResourceFile ? [value.uploadResourceFile] : [];
                    } else if (propName === 'confirmHr') {
                        tmpObj[propName] = value ? '0' : '';
                    } else {
                        tmpObj[propName] = value;
                    }
                });
                const data = {
                    id: leaveOfficeId || '',
                    currentAction: 'forwardToNextTask',
                    processTemplateId: leaveOfficeId ? detail.processTemplateId : processTemplateId,
                    processInstanceId: leaveOfficeId ? detail.processInstanceId : processInstanceId,
                    relatedBusinessObject: {
                        ...tmpObj,
                        id: relatedBusinessObject.id || ''
                    }
                };
                if (otherPost) {
                    data.relatedBusinessKey = `departmentId:${values.departmentId}`;
                }
                if (detail.relatedBusinessKey) {
                    data.relatedBusinessKey = detail.relatedBusinessKey;
                }
                console.info('data:', data);
                const response = await processPush(data);
                if (response.code === 10000) {
                    message.success('提交成功！');
                    history.push('/personal/portal/myOnboardAndLeave/myQuitManagement');
                } else {
                    message.error(response.msg);
                    setSubmitLoading(false);
                }
            }
        });
    };
    const handleReject = async () => {
        setRejectLoading(true);
        const data = {
            currentAction: 'backwardToPreviousTask',
            processTemplateId: detail.processTemplateId,
            processInstanceId: detail.processInstanceId,
            id: leaveOfficeId || '',
            relatedBusinessObject: {
                employeeCode: relatedBusinessObject.employeeCode,
                companyId: relatedBusinessObject.companyId
            }
        };

        console.info('data:', data);
        const response = await processPush(data);
        if (response.code === 10000) {
            message.success('退回成功！');
            history.push('/personal/portal/myOnboardAndLeave/myQuitManagement');
        } else {
            message.error(response.msg);
            setRejectLoading(false);
        }
    };
    const handleCancel = async () => {
        setCancelLoading(true);
        const response = await processPush({
            currentAction: 'resetToFirstTask',
            id: leaveOfficeId || '',
            processTemplateId: detail.processTemplateId,
            processInstanceId: detail.processInstanceId
        });

        if (response.code === 10000) {
            message.success('撤销成功！');
            history.push('/personal/portal/flow/mine/list');
        } else {
            message.error(response.msg);
            setCancelLoading(false);
        }
    };

    return {
        handleSubmit,
        handleReject,
        handleCancel,
        onlyCheck,
        submitLoading,
        rejectLoading,
        cancelLoading
    };
};

/**
 * 动态修改标签页名称
 * @param otherPost 是否是 HR 发起申请
 * @param dispatch
 * @param location
 */
export const useDynamicTitle = (otherPost, dispatch, location) => {
    // 动态更改标签显示名称
    useEffect(() => {
        dispatch({
            type: 'menu/changeMenuName',
            payload: {
                path: location.pathname,
                newName: otherPost ? '办理离职' : '离职申请'
            }
        });

        return () => {
            dispatch({
                type: 'menu/changeMenuName',
                payload: {
                    path: location.pathname,
                    newName: '离职申请'
                }
            });
        };
    }, [otherPost]);
};
